/**
 * Social Recommend
 * Implements the same CRUD terminology
 *
 * @author Seth
 * @version 0.1
 */
Social.Recommend = function(){
	var s = {},
		max = 200,
		// create (C)
		_create = function() {
			var emails = s.loc.find('[name="recommend_body"]').val();
			
	    	Petolio.ajax({
				url: 'social/create',
				type: 'post',
				data: {id: s.id, scope: s.scope, plugin: 'recommend', emails: emails},
				cache: false,
				success: function (x) {
					_read();
					Petolio.showMessage(_translate('sent').replace('%s', x.count));
				},
				error: function (x) {
					Petolio.showMessage(x.msg);
				}
			});

		// read (R)
		},	_read = function() {
	    	Petolio.ajax({
				url: 'social/read',
				type: 'post',
				data: {id: s.id, scope: s.scope, plugin: 'recommend'},
				cache: false,
				success: function (x) {
					s.loc.show();
					s.loc.html(x.html);
					_bind();
					Social.done();
				}
			});

		// update (U)
		},	_update = function() {

		// delete (D)
		},	_delete = function(e) {

		// bind events
		},	_bind = function() {
			s.loc.find('[name="recommend_body"]').focus(_focus);
			s.loc.find('[name="recommend_body"]').blur(_blur);
			s.loc.find('[name="recommend_body"]').keyup(_limit);
			s.loc.find('[name="recommend_body"]').keydown(_limit);
			s.loc.find('[name="recommend_submit"]').click(_save);

		// call create or update
		},	_save = function() {
			var emails = s.loc.find('[name="recommend_body"]');

			// reset error
			emails.css({borderColor: '#ccc'});

			// check length
			if(emails.val() == _translate('blank') || !emails.val().length > 0) {
				emails.css({borderColor: 'red'});
				return false;
			}

			// call create
			_create();
			
		// textarea focus
		},	_focus = function() {
			if($(this).val() == _translate('blank'))
				$(this).val('');

		// textarea blur
		},	_blur = function() {
			if(!$(this).val())
				$(this).val(_translate('blank'));
			
		// textarea limit
		},	_limit = function(e) {
			var count = s.loc.find('[class="recommend_count"]');

			// limit chars
			if ($(this).val().length > max) {
			    $(this).val($(this).val().substring(0, max));
			    this.scrollTop = this.scrollHeight;
			} else
			    count.html(max - $(this).val().length);

		// translation handle
		},	_translate = function(i) {
			var t = s.loc.find('[class="recommend_translate"]'),
				o = $.parseJSON(t.html());

			return o[i];
			    
		// plugin constructor
		},	__construct = function(win, params) {
			s.loc = win.find('.recommend');
			s.id = params.id;
			s.scope = params.scope;
			s.win = win;

			_read();
		};

	// public
	return {
		load: __construct
	}
}();